<?php

namespace common\logics;

use Yii;
use common\base\Model;
use common\helpers\Utils;
use common\helpers\ArrayHelper;
use apiend\models\User;

/**
 * 短信验证码发送模型
 * SmsCaptchaForm
 */
class SmsCaptchaForm extends Model {

    use \common\traits\Constants;

    const TPL_AUTH_CODE = 'SMS_134245055';
    //
    const SCOPE_LOGIN = 'login';
    const SCOPE_REGISTER = 'register';
    const SCOPE_FORGET = 'forget';
    const SCOPE_SIGNIN = 'signin';
    const SCOPE_BIND = 'bind';
    const SCOPE_PUBLISH = 'publish';
    const SCOPE_ACCOUNT = 'account';
    //
    const LIMIT_SEND_TIMES = 500;
    const AUTO_FLUSH_DURATION = 86400;
    const CAPTCHA_EXPIRE_TIME = 600;
    const SEND_PERIOD_TIME = 60;

    public $scope;
    public $mobile;
    //
    private $_sendtimes = 0;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['mobile', 'scope'], 'required'],
            ['scope', 'in', 'range' => static::getAttributeMark('scope'), 'message' => '{attribute}不在允许的列表内'],
            ['mobile', '\common\validators\MobileValidator'],
            ['scope', 'validateSendscope'],
            ['mobile', 'validateSendRateLimit'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels() {
        return [
            'mobile' => '手机号',
            'scope' => '标识范围',
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateSendscope($attribute) {
        if (!$this->hasErrors()) {
            if ($this->$attribute == self::SCOPE_PUBLISH) {
                return;
            }
            $entryMobile = Yii::$app->security->generatePrivateKey($this->mobile);
            $exists = User::find()->where(['mobile' => $entryMobile])->exists();
            if ($this->$attribute == self::SCOPE_SIGNIN) {
                if ($exists) {
                    $this->$attribute = self::SCOPE_LOGIN;
                } else {
                    $this->$attribute = self::SCOPE_REGISTER;
                }
            } else if ($this->$attribute == self::SCOPE_REGISTER || $this->$attribute == self::SCOPE_BIND) {
                if ($exists) {
                    $this->addError($attribute, '当前手机号已被占用');
                }
            } else {
                if (!$exists) {
                    $this->addError($attribute, '当前手机号未注册帐号');
                }
            }
        }
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validateSendRateLimit($attribute) {
        if (!$this->hasErrors()) {
            if ($this->sendTimes >= static::LIMIT_SEND_TIMES) {
                $this->addError($attribute, '超过了短信发送的限制次数，24小时之内将屏蔽当前手机号的短信发送。');
            }
            $period = Yii::$app->cache->get('period_' . $this->scope . '_' . $this->mobile);
            if ($period) {
                $waitsecond = $period + static::SEND_PERIOD_TIME - time();
                if ($waitsecond > 0) {
                    $this->addError($attribute, '重发倒计时剩余：' . $waitsecond . '秒');
                }
            }
        }
    }

    public function getSendTimes() {
        $sendtimes = Yii::$app->cache->get('sendtimes_' . $this->scope . '_' . $this->mobile);
        if ($sendtimes) {
            $this->_sendtimes = $sendtimes;
        }
        return $this->_sendtimes;
    }

    /**
     * 发送短信校验码
     * @return User|null the saved model or null if saving fails
     */
    public function send() {
        if (!$this->validate()) {
            $this->dumpError('', $this->getFirstErrors());
        }

        $captcha = $this->generateCaptcha();
        //提交短信发送
        $status = Yii::$app->dysms->sendSms($this->mobile, static::TPL_AUTH_CODE, [
            'code' => $captcha,
        ]);

        $data = [
            'send_status' => true,
            'receive_mobile' => $this->mobile,
            'scope_times' => $this->_sendtimes,
            'message' => '发送成功',
        ];
        if ($status !== true) {
            $data['send_status'] = false;
            $data['message'] = $status;
        } else {
            Yii::$app->cache->set('period_' . $this->scope . '_' . $this->mobile, time(), static::SEND_PERIOD_TIME);
            Yii::$app->cache->set('sendtimes_' . $this->scope . '_' . $this->mobile, $this->_sendtimes + 1, static::AUTO_FLUSH_DURATION);
            $data['scope_times'] += 1;
            if (YII_ENV_DEV || YII_DEBUG) {
                $data['captcha'] = $captcha;
            }
        }

        return $data;
    }

    /**
     * 生成短信校验码
     * @return string
     */
    protected function generateCaptcha() {
        $length = 4;
        if ($this->scope == static::SCOPE_FORGET || $this->scope == static::SCOPE_BIND) {
            $length = 6;
        }

        $captcha = !YII_DEBUG ? Utils::random($length, true) : str_pad('8', $length, '8');
        Yii::$app->cache->set('captcha_' . $this->scope . '_' . $this->mobile, $captcha, static::CAPTCHA_EXPIRE_TIME);
        return $captcha;
    }

}
